package com.hcl.orm.core.spring;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.util.StringUtils;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Set;

/**
 * @author hucl
 * @projectName jim-orm
 * @description: TODO
 * @date 2021/5/1217:26
 */
public class ClassPathMultiDialectDaoScanner extends ClassPathBeanDefinitionScanner {
    private Class<? extends Annotation> annotationClass;
    private String jdbcOperationsBeanName;
    private BeanFactory beanFactory;

    public ClassPathMultiDialectDaoScanner(BeanDefinitionRegistry registry) {
        super(registry, false);
    }

    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitions = super.doScan(basePackages);
        if (beanDefinitions.isEmpty()) {
            logger.warn("No  dao was found in '" + Arrays.toString(basePackages) + "' package. Please check your configuration.");
        } else {
            try {
                processBeanDefinitions(beanDefinitions);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return beanDefinitions;

    }

    @Override
    protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
        if (super.checkCandidate(beanName, beanDefinition)) {
            return true;
        } else {
            logger.warn("Skipping MultiDialectDaoFactoryBean with name '" + beanName
                    + "' and '" + beanDefinition.getBeanClassName() + "' daoInterface"
                    + ". Bean already defined with the same name!");
            return false;
        }
    }

    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return (beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent());
    }


    public void registerFilters() {
        boolean acceptAllInterfaces = true;
        // if specified, use the given annotation and / or marker interface
        if (this.annotationClass != null) {
            addIncludeFilter(new AnnotationTypeFilter(this.annotationClass));
            acceptAllInterfaces = false;
        }
        if (acceptAllInterfaces) {
            // default include filter that accepts all classes
            addIncludeFilter((metadataReader, metadataReaderFactory) -> true);
        }
        // exclude package-info.java
        addExcludeFilter((metadataReader, metadataReaderFactory) -> {
            String className = metadataReader.getClassMetadata().getClassName();
            return className.endsWith("package-info");
        });
    }

    private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitions) throws ClassNotFoundException {
        for (BeanDefinitionHolder holder : beanDefinitions) {
            GenericBeanDefinition definition = (GenericBeanDefinition) holder.getBeanDefinition();
            DaoMethodCacheManager.register(Class.forName(definition.getBeanClassName()));
            definition.getPropertyValues().add("daoInterface", definition.getBeanClassName());
            definition.setBeanClass(MultiDialectDaoFactoryBean.class);

            boolean explicitFactoryUsed = false;
            if (StringUtils.hasText(this.jdbcOperationsBeanName)) {
                definition.getPropertyValues().add("jdbcOperations", new RuntimeBeanReference(this.jdbcOperationsBeanName));
                explicitFactoryUsed = true;
            }
//            definition.getPropertyValues().add("jdbcOperations", new RuntimeBeanReference(this.jdbcOperationsBeanName));
            if (!explicitFactoryUsed) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Enabling autowire by type for DaoFactoryBean with name '" + holder.getBeanName() + "'.");
                }
                definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
            }

        }
    }

    public void setAnnotationClass(Class<? extends Annotation> annotationClass) {
        this.annotationClass = annotationClass;
    }

    public void setJdbcOperationsBeanName(String jdbcOperationsBeanName) {
        this.jdbcOperationsBeanName = jdbcOperationsBeanName;
    }
}
